package com.tom.architect.party3.day30;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import com.tom.architect.R;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity30 extends AppCompatActivity {
    private static final String TAG = "MainActivity30";
    private ImageView action_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main30);
        action_image = findViewById(R.id.action_image);

        new Thread(new Runnable() { // 开启线程执行下载任务。
            @Override
            public void run() {
                doJust();
            }
        }).start();
    }

    private void doJust() {
        String urlStr = "http://pic-bucket.ws.126.net/photo/0003/2024-01-12/IO8BIBJV00AJ0003NOS.jpg";

        Observable.just(urlStr) // ObservableJust
                .map(new Function<String, Bitmap>() { // ObservableMap
                    @Override
                    public Bitmap apply(String urlStr) throws Exception {
                        // 第五步：下载图片
                        URL url = new URL(urlStr);
                        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                        InputStream inputStream = urlConnection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        return bitmap;
                    }
                })
                .subscribe(new Consumer<Bitmap>() { // ObservableMap 是实现类。
                    @Override
                    public void onNext(Bitmap bitmap) {
                        // 第七步：显示图片。切换到UI线程再显示。
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                action_image.setImageBitmap(bitmap);
                            }
                        });
                    }
                });
    }

}